import React from 'react'
import {useState,useEffect,useRef} from "react"
import axios from 'axios'
function App() {
    let myref = useRef(null)
    let [index1,activeIndex1] = useState(0)

   let [arr,setArr] = useState([])
   useEffect(()=>{
        axios.get("/list1").then(res=>{
            setArr(res.data)
        })
        setTimeout(()=>{
            window.addEventListener("scroll",handleScroll,true)
        },100)
   },[])
   let handleScroll = ()=>{
       // 获取右侧div滚动的距离
       let topS = myref.current.scrollTop
       console.log(topS);
       console.log(myref.current.children); 
       let arr = Array.from(myref.current.children)
       console.log(arr);
       arr.forEach((item,index)=>{
           if (topS >  item.offsetTop) { 
               // 如果右侧盒子滚动的距离大于当前盒子距离顶部的距离，就让当前盒子对应左侧的tab高亮
            activeIndex1(index)
           }
       })
   }
   let changeIndex = (index)=>{
        console.log(index);
        activeIndex1(index)
        // scrollIntoView 将一个元素滚动到浏览器最顶端
        myref.current.children[index].scrollIntoView({behavior:"smooth"})
   }
  return (
    <div className='wrap'>
        <div className='left'>
            {
                arr && arr.length ? arr.map((item,index)=>{
                    return <div key={index} className={index===index1?"active":""} onClick={()=>changeIndex(index)} style={{height:"40px",lineHeight:"40px",textAlign:"center"}}>{item.title}</div>
                }):"暂无数据"
            }
        </div>
        <div className='right' ref={myref}>
            
                {
                    arr && arr.length ? arr.map((item,index)=>{
                        return <div key={index}>
                             <h4>{item.title}</h4>
                             <div className='childbox'>
                             {
                                 item.children &&  item.children.length ?  item.children.map((ite,inde)=>{
                                    return <div key={inde}>
                                            <img src={ite.img} alt="" />
                                            <h5>{ite.name}</h5>
                                    </div>
                                 }):"暂无数据"
                             }
                             </div>
                            
                        </div>
                    }):"暂无数据"
                }
            
        </div>
    </div>
  )
}

export default App